package com.situ.mall.admin.controller;

import com.situ.mall.admin.service.IUserService;
import com.situ.mall.admin.util.RequestUtil;
import com.situ.mall.admin.vo.ForgetPasswordVO;
import com.situ.mall.admin.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/")
public class LoginController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/login")
    public String login() {

        redisTemplate.opsForValue().set("test1","adadadada");
        redisTemplate.opsForValue().set("test2","aaaa",5, TimeUnit.MINUTES);
        return "login";
    }

    @GetMapping("/logout")
    public String logout() {
        RequestUtil.getSession().removeAttribute("currentMember");
        return "login";
    }

    //忘记密码根据匹配的用户名和电话修改密码且为加密存储
    @GetMapping("/forgetPassword")
    public String logon() {
        return "forgetPassword";
    }

    @PostMapping("/checkPhone")
    @ResponseBody
    public ResultVO checkPhone(ForgetPasswordVO forgetPass) {

        return userService.checkPhone(forgetPass);
    }




    //登录验证
    @PostMapping("/login")
    public String loginCheck(HttpServletRequest request, Model model) {
       // String super1 = request.getParameter("super1");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        System.out.println(username+","+password + ","+captcha);
        //Integer adminSuper1=0;

        if (!((String.valueOf(request.getSession().getAttribute("captcha"))).equals(captcha))) {
            model.addAttribute("msg", "验证码错误");
            return "login";
        } else {

            Boolean right = userService.check(username, password,request.getSession());
            //调用service检查是否正确
            if (right) {
                return "redirect:/index";
            } else {
                  //重定向到login
                model.addAttribute("msg", "用户名密码错误");
                return "login";
            }

        }
    }
}
